/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.theyeasy.dvmini.service.impl
 *
 *    Filename:    ProjectServiceImpl.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月22日 下午5:53:36
 *
 *    Revision:
 *
 *    2017年10月22日 下午5:53:36
 *        - first revision
 *
 *****************************************************************/
package com.theyeasy.dvmini.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.theyeasy.weixin.util.WxMiniUtil;

import com.google.common.base.Strings;
import com.theyeasy.dvmini.dao.PosterLogDao;
import com.theyeasy.dvmini.dao.PostertempletDao;
import com.theyeasy.dvmini.dao.ProjectDao;
import com.theyeasy.dvmini.dao.SalesDao;
import com.theyeasy.dvmini.model.Posterlog;
import com.theyeasy.dvmini.model.Postertemplet;
import com.theyeasy.dvmini.model.Projects;
import com.theyeasy.dvmini.model.Sales;
import com.theyeasy.dvmini.service.PosterService;
import com.theyeasy.dvmini.util.CommonUtil;
import com.theyeasy.dvmini.util.ImageUtil;
import com.theyeasy.dvmini.util.PageResults;
import com.theyeasy.dvmini.util.StringUtil;
import com.theyeasy.dvmini.vo.Vo_msg;

import sun.awt.image.ImageFormatException;
import tk.mybatis.mapper.entity.Example;

/**
 * @ClassName ProjectServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月22日 下午5:53:36
 * @version 1.0.0
 */
@Service
public class PosterServiceImpl implements PosterService {

    @Autowired
    PostertempletDao PostertempletDao;

    @Autowired
    PosterLogDao posterlogDao;

    @Autowired
    ProjectDao projectDao;

    @Autowired
    SalesDao saleDao;

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#getPosterList(java.lang.Integer, java.lang.String)
     */
    @Override
    public PageResults<Postertemplet> getPosterList(Integer page) {
        // TODO Auto-generated method stub
        Example example = new Example(Postertemplet.class);
        example.createCriteria().andEqualTo("deleted", false);
        RowBounds row = new RowBounds((page - 1) * 10, 10);
        example.setOrderByClause(" id desc ");
        List<Postertemplet> list = PostertempletDao.selectByExampleAndRowBounds(example, row);
        int total = PostertempletDao.selectCountByExample(example);
        PageResults<Postertemplet> pageresult = new PageResults<>();
        pageresult.setPage(page);
        pageresult.setTotal(total);
        pageresult.setRows(list);
        pageresult.setPageSize(5);
        return pageresult;
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#addPoster(java.lang.String, java.lang.String, int, int, int, int,
     * int)
     */
    @Override
    public String addPoster(String name, String imgurl, int x, int y, int width, int height, int posttype) {
        // TODO Auto-generated method stub
        Postertemplet poster = new Postertemplet();
        poster.setName(name);
        poster.setImgurl(imgurl);
        poster.setX(x);
        poster.setY(y);
        poster.setWidth(width);
        poster.setHeight(height);
        poster.setPostertype(posttype);
        poster.setDeleted(false);
        poster.setUpdatedtime(CommonUtil.getTime());
        int row = PostertempletDao.insertSelective(poster);
        return row > 0 ? "ok" : "添加失败，数据异常";
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#updatePoster(java.lang.Integer, java.lang.String,
     * java.lang.String, int, int, int, int, int)
     */
    @Override
    public String updatePoster(Integer id, String name, String imgurl, int x, int y, int width, int height,
            int posttype) {
        Postertemplet poster = PostertempletDao.selectByPrimaryKey(id);
        if (poster == null)
            return "修改失败，数据异常";
        boolean isclear = false;
        if (!poster.getImgurl().equals(imgurl) || poster.getX() != x || poster.getY() != y
                || poster.getWidth() != width) {

            isclear = true;
        }
        poster.setName(name);
        poster.setImgurl(imgurl);
        poster.setX(x);
        poster.setY(y);
        poster.setWidth(width);
        poster.setHeight(height);
        poster.setPostertype(posttype);
        poster.setUpdatedtime(CommonUtil.getTime());
        if (isclear) {
            // 修改了模板信息则将生成的海报清空
            System.out.println("清空历史生成海报记录");
            ClearSalesImgurl(id);
        }
        int row = PostertempletDao.updateByPrimaryKeySelective(poster);
        return row > 0 ? "ok" : "修改失败，数据异常";
    }

    void ClearSalesImgurl(Integer templetid) {
            Example example = new Example(Sales.class);
            example.createCriteria().andEqualTo("deleted", false);
            List<Sales> saleslist = saleDao.selectByExample(example);
            if (saleslist != null && saleslist.size() > 0) {
                  for (Sales sale : saleslist) {
                        Sales newsale = new Sales();
                        newsale.setId(sale.getId());
                        newsale.setImgurl("");
                        newsale.setMediaid("");
                        saleDao.updateByPrimaryKeySelective(newsale);
                   }
               }
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#deletePoster(java.lang.Integer)
     */
    @Override
    public String deletePoster(Integer id) {
        Postertemplet poster = PostertempletDao.selectByPrimaryKey(id);
        if (poster == null)
            return "删除失败，数据异常";
        poster.setDeleted(true);
        int row = PostertempletDao.updateByPrimaryKeySelective(poster);
        return row > 0 ? "ok" : "删除失败，数据异常";
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#getPoster(java.lang.Integer)
     */
    @Override
    public Postertemplet getPoster(Integer id) {

        return PostertempletDao.selectByPrimaryKey(id);
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#getPosterLog(java.lang.Integer)
     */
    @Override
    public PageResults<Posterlog> getPosterLog(Integer page, String keyword, Integer postertype) {
        Example example = new Example(Posterlog.class);
        example.createCriteria().andEqualTo("deleted", false);
        RowBounds row = new RowBounds((page - 1) * 10, 10);
        if (!Strings.isNullOrEmpty(keyword)) {
            example.createCriteria().andLike("name", "%" + keyword + "%");
        }
        if (!StringUtil.isZearoOrNull(postertype)) {
            example.createCriteria().andEqualTo("postertype", postertype);
        }
        example.setOrderByClause(" id desc ");
        List<Posterlog> list = posterlogDao.selectByExampleAndRowBounds(example, row);
        int total = posterlogDao.selectCountByExample(example);
        PageResults<Posterlog> pageresult = new PageResults<>();
        pageresult.setPage(page);
        pageresult.setTotal(total);
        pageresult.setRows(list);
        pageresult.setPageSize(5);
        return pageresult;
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#addPosterLog(java.lang.Integer, java.lang.Integer,
     * java.lang.String, java.lang.String, java.lang.Integer)
     */
    @Override
    public void addPosterLog(Integer postertype, Integer personid, String name, String imgurl, Integer posterid) {
        Posterlog log = new Posterlog();
        log.setImgurl(imgurl);
        log.setName(name);
        log.setPersonid(personid);
        log.setPosterid(posterid);
        log.setPostertype(postertype);
        log.setDeleted(false);
        log.setUpdatedtime(CommonUtil.getTime());
        posterlogDao.insertSelective(log);
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#GeneratePosterJPG(java.lang.Integer, java.lang.String)
     */
    @Transactional
    @Override
    public Vo_msg GeneratePosterJPG(Integer saleid) {

        Sales sale = saleDao.selectByPrimaryKey(saleid);
        if (sale == null || (sale != null && Strings.isNullOrEmpty(sale.getWxopenid())))
            return new Vo_msg(-1, "生成海报失败，不存在该销售人员");

        // 如果存在则直接返回海报图片
        if (!Strings.isNullOrEmpty(sale.getImgurl())) {
            return new Vo_msg(0, sale.getImgurl());
        }

        // 获取项目模板信息
        Postertemplet templet = null;
        Example example = new Example(Postertemplet.class);
        example.createCriteria().andEqualTo("deleted", false);
        example.setOrderByClause(" id desc ");
        List<Postertemplet> list = PostertempletDao.selectByExample(example);
        if (list != null && list.size() > 0) {
            templet = list.get(0);
        }

        if (templet == null || (templet != null && Strings.isNullOrEmpty(templet.getImgurl())))
            return new Vo_msg(-1, "生成海报失败，项目海报模板不存在");

        String qCodeUrl = "";// 小程序码路径
        String scene = "";
        String posterurl = "";// 海报模板
        try {
            scene = URLEncoder.encode(saleid + "", "utf-8");
            // 获取小程序码
            qCodeUrl = WxMiniUtil.getMiniCode2(scene, "", templet.getWidth(), true, 0, 255, 0);
            System.out.println("qCodeUrl:" + qCodeUrl);
            if (Strings.isNullOrEmpty(qCodeUrl)) {
                return new Vo_msg(-1, "获取小程序码失败");
            }
            // 获取小程序码图片路径
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/");
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            String newqrcodeUri = realPath + qCodeUrl;
            System.out.println("newqrcodeUri:" + newqrcodeUri);

            posterurl = ImageUtil.GenerateJPGImg(templet.getImgurl(), newqrcodeUri, templet.getX(), templet.getY(),
                    templet.getWidth());
            System.out.println("posterurl：" + posterurl);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return new Vo_msg(-1, "生成海报失败" + e.getMessage());
        }
         // 修改销售的海报图片
         sale.setImgurl(posterurl);
         saleDao.updateByPrimaryKeySelective(sale);
         return new Vo_msg(0, posterurl);
    }

    /*
     * (非 Javadoc) Description:
     * @see com.theyeasy.dvmini.service.PosterService#getAllPostertemplet()
     */
    @Override
    public List<Postertemplet> getAllPostertemplet() {
        Example example = new Example(Postertemplet.class);
        example.createCriteria().andEqualTo("deleted", false);
        List<Postertemplet> list = PostertempletDao.selectByExample(example);
        return list;
    }
}
